package com.snopy.concurrency.hashmap;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Supplier;

/**
 * @author snopy
 * @version 1.0.0
 * @classname CountWord
 * @description
 * @email 77912204@qq.com
 * @date 2022/06/30 16:59
 */
@Slf4j
public class CountWord {

    static ExecutorService service = Executors.newFixedThreadPool(26);
    CountDownLatch latch = new CountDownLatch(26);
    public static void main(String[] args) {
        new CountWord().summary();
        //service.shutdown();
    }
    private void summary(){
        ConcurrentHashMap<String,LongAdder> map = new ConcurrentHashMap<>();
        List<Future<?>> list = new ArrayList<>();
        for (int i = 0; i < 26; i++) {
            int k = i;
            Future<?> submit = service.submit(() -> {
                try {
                    BufferedReader bufferedReader = new BufferedReader(
                            new InputStreamReader(
                                    new FileInputStream("F:/workspaceA/Sonata/Sonata_test/src/main/resources/temp/" + (k + 1) + ".txt")));
                    bufferedReader.lines().forEach(s -> {
               /*         Integer count = map.get(s);
                        count = count == null?1:count+1;
                        map.put(s,count);*/
                            map.computeIfAbsent(s, v -> new LongAdder()).increment();

                    });
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            });
            try {
                submit.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
            list.add(submit);
        }
        list.forEach(x->{
            try {
                x.get();
                latch.countDown();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }

        });
        try {
            latch.await();
            log.debug("{},",map);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        service.shutdown();
    }
}

